package com.study.meng.bigevent.common.interceptor;

import cn.hutool.jwt.JWTUtil;
import com.study.meng.bigevent.common.utils.ThreadLocalUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        response.setContentType("application/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        if (token == null && !JWTUtil.verify(token, "meng".getBytes())) {
            response.getWriter().write("{\"status\": 401, \"message\": \"请提供正确的token\"}");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        //解析token获取用户id
        Integer userId = Integer.valueOf(JWTUtil.parseToken(token).getPayload("id").toString());
        //比对redis中是否存在token
        String redisToken = redisTemplate.opsForValue().get("Login:token:" + userId);
        if (redisToken == null) {
            response.getWriter().write("{\"status\": 401, \"message\": \"未登陆或已过期\"}");
            return false;
        }
        ThreadLocalUtil.setCurrentUser(userId);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // Clear ThreadLocal after request processing
        ThreadLocalUtil.remove();
    }
}
